using Admin2025.Application.Services;
using Admin2025.Api.Dto;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Admin2025.Application.common;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly AuthService _authService;
    private readonly IConfiguration _configuration;
    public AuthController(AuthService authService, IConfiguration configuration)
    {
        _authService = authService;
        _configuration = configuration;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(UserRegisterDto userRegisterDto)
    {
        await _authService.RegisterAsync(userRegisterDto.Username, userRegisterDto.Password);
        return Ok("注册成功");
    }
    [HttpPost("login")]
    public async Task<IActionResult> Login(UserLogingDto userLogingDto)
    {
        var res = await _authService.LoginAsync(userLogingDto.Username, userLogingDto.Password);
        if (res.Code == 0)
        {
            var jwtSettings = _configuration.GetSection("JwtSettings");
            var secretKey = jwtSettings["SecretKey"];
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings["Audience"];

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, userLogingDto.Username),
                new Claim(ClaimTypes.Role, "User") // 根据用户角色动态设置
            };
            var tokenHandler = new JwtSecurityTokenHandler();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
            var key = Encoding.UTF8.GetBytes(secretKey);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.UtcNow.AddMinutes(30),
                Issuer = issuer,
                Audience = audience,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var jwtToken = tokenHandler.WriteToken(token);

            return Ok(new { token = jwtToken });

        }
        return Ok(res);
    }
}